package com.czxy.changgou3.com.czxy.changgou3.service;

import com.czxy.changgou3.com.czxy.changgou3.mapper.CategoryMapper;
import com.czxy.changgou3.pojo.Category;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangmengxiang1@itcast.cn
 * @version 1.0
 * @date 2020/4/22
 */
@Service
@Transactional
public class CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    public List<Category> findAll(){
        //1 查询排序所有分类
        Example example = new Example(Category.class);
        example.setOrderByClause("parent_id asc");
        List<Category> categoryList = categoryMapper.selectByExample(example);

        //2 处理分类，将所有字符串添加到父分类List集合中
        //2.1 处理后的所有数据
        List<Category> returnList = new ArrayList<>();
        //准备一个map集合 用于存父分类
        Map<Integer, Category> cacheMap = new HashMap<>();
        //便利数据
        for (Category category : categoryList) {
            //1）将所有一级分类添加集合中
            if (category.getParentId() == 0){
                returnList.add(category);
            }
            //2）子分类可以找到一级分类，保存一级分类
            cacheMap.put(category.getId(),category);
            //3）子分类获得父分类，酱紫分类添加到父分类集合中
            Category parentCategory = cacheMap.get(category.getParentId());
            if (parentCategory != null){
                parentCategory.getChildren().add(category);
            }
        }
        return returnList;
    }
}
